package com.mt.linkedlist;

/**
 * 链表操作
 */
public class LinkedListOperate {

    public static class Node {
        public int value;

        public Node next;

        public Node(int value) {
            this.value = value;
        }
    }

    public static class DoubleNode {
        public int value;

        public DoubleNode last;

        public DoubleNode next;

        public DoubleNode(int data) {
            value = data;
        }
    }


    /**
     * 反转单链表
     * @param head
     * @return
     */
    public static Node reverseLinkedList(Node head) {
        Node pre = null;
        Node next = null;
        while (null != head) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

    /**
     * 反转双向链表
     * @param head
     * @return
     */
    public static DoubleNode reverseDoubleLinedList(DoubleNode head){
        DoubleNode pre = null;
        DoubleNode next = null;
        while (null != head){
            next = head.next;
            head.next = pre;
            head.last = next;
            pre = head;
            head = next;
        }
        return pre;
    }

    public static void main(String[] args) {

        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        node3.next = node4;
        node2.next = node3;
        node1.next = node2;
        Node nodeResult = reverseLinkedList(node1);
        System.out.println(nodeResult);

        DoubleNode node11 = new DoubleNode(1);
        DoubleNode node22 = new DoubleNode(2);
        DoubleNode node33 = new DoubleNode(3);
        DoubleNode node44 = new DoubleNode(4);
        node11.next = node22;
        node22.next = node33;
        node22.last = node11;
        node33.next = node44;
        node33.last = node22;
        node44.last = node33;

        DoubleNode doubleNodeResult = reverseDoubleLinedList(node11);
        System.out.println(doubleNodeResult);

    }
}
